package com.ruoyi.framework.aspectj;

import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DatabaseConnectionAspect {

    @Value("${app.security.token:}")
    private String securityToken;

    @Value("${spring.datasource.druid.master.url:}")
    private String dbUrl;

    @Value("${spring.datasource.druid.master.username:}")
    private String dbUsername;

    private static boolean tokenValidated = false;

    @Around("execution(* javax.sql.DataSource.getConnection(..))")
    public Object validateTokenBeforeConnection(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!tokenValidated) {
            validateToken();
            tokenValidated = true;
        }

        return joinPoint.proceed();
    }

    private void validateToken() {
        if (StringUtils.isEmpty(securityToken)) {
            throw new SecurityException("No security token provided");
        }

        String currentToken = generateCurrentToken();
        if (!securityToken.equals(currentToken)) {
            throw new SecurityException("Invalid security token. Database access denied.");
        }
    }

    public String generateCurrentToken() {
        try {
            // 只基于数据库URL和用户名生成token
            StringBuilder tokenBuilder = new StringBuilder();

            // 添加数据库连接信息
            tokenBuilder.append(dbUrl);
            tokenBuilder.append(dbUsername);

            // 可以添加应用特定的标识符增加安全性
            tokenBuilder.append("hazard_tracking_app");

            return DigestUtils.sha256Hex(tokenBuilder.toString());
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate database token", e);
        }
    }
}
